<script setup>
import { ref, onMounted, watch } from 'vue';
import { getCarbonList, getAdvice, saveRecord } from '@/api/Carbon.js';
import { ElMenu, ElMenuItem, ElInput, ElButton, ElMessage, ElCard, ElMessageBox } from 'element-plus';
import { useUserStore } from "@/stores/user";

const types = [
  { id: 0, name: '电力' },
  { id: 1, name: '能源' },
  { id: 2, name: '交通工具' },
  { id: 3, name: '食物' },
  { id: 4, name: '废物' },
  { id: 5, name: '消费品' },
  { id: 6, name: '建筑材料' }
];

const selectedType = ref(1);
const items = ref([]);
const selectedItem = ref(null);
const quantity = ref(0);
const result = ref(null);
const advices = ref([]);
const loadingAdvice = ref(false); // Loading state for advice
const  store = useUserStore();
const fetchItems = async () => {
  const response = await getCarbonList(selectedType.value);
  if (response.data.code === 200) {
    items.value = response.data.data;
  } else {
    ElMessage.error('获取数据失败');
  }
};

const calculateFootprint = async () => {
  if (selectedItem.value && quantity.value) {
    result.value = (selectedItem.value.value * quantity.value).toFixed(2);
  }
  loadingAdvice.value = true; // Start loading state
  try {
    const adviceResponse = await getAdvice(selectedItem.value.name, quantity.value, selectedItem.value.unit, result.value);
    advices.value = adviceResponse.data.data;
  } catch (error) {
    ElMessage.error('获取建议失败');
  } finally {
    loadingAdvice.value = false; // End loading state
  }
};

const selectItem = (item) => {
  selectedItem.value = item;
};

const updateType = (key) => {
  selectedType.value = parseInt(key);
  fetchItems();
};

const saveFootprintRecord = async () => {
  if (!selectedItem.value || !quantity.value) return;

  const data = {
    userId: store.UserId, // Assuming the userId is stored here
    carbonFactorId: selectedItem.value.id,
    name: selectedItem.value.name,
    value: quantity.value,
    unit: selectedItem.value.unit,
    icon: selectedItem.value.icon,
    type: selectedType.value,
    result: parseFloat(result.value)
  };

  try {
    await ElMessageBox.confirm('确认要保存该碳足迹记录吗？', '确认保存', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await saveRecord(data);
    if (response.data.code === 200) {
      ElMessage.success('保存成功');
    } else {
      ElMessage.error('保存失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('保存失败');
    }
  }
};

onMounted(fetchItems);
watch(selectedType, fetchItems);
</script>


<template>
  <div class="carbon-footprint-page">
    <h2 style="text-align: center">🌿 碳足迹计算器 🌿</h2>

    <!-- 水平导航栏样式的类型切换 -->
    <el-menu style="width: 1400px" mode="horizontal" :default-active="selectedType.toString()" @select="updateType">
      <el-menu-item style="margin-left: 7%" v-for="type in types" :key="type.id" :index="type.id.toString()">
        {{ type.name }}
      </el-menu-item>
    </el-menu>

    <!-- 直接展示项目 -->
    <div style="margin-left: 10%" v-if="items.length > 0" class="item-selection">
      <el-button
          v-for="item in items"
          :key="item.id"
          @click="selectItem(item)"
          :type="selectedItem === item ? 'success' : 'default'"
          style="margin: 20px;"
      >
        <img style="width: 25px; height: 25px" :src="item.icon">
        <span style="margin-left: 5px" v-text="item.name"></span>
      </el-button>
    </div>

    <!-- 输入数量和计算结果 -->
    <div v-if="selectedItem" class="calculation-section">
      <el-input v-model.number="quantity" placeholder="请输入数量" type="number" min="0" style="width: 200px;" />
      <p>单位: {{ selectedItem.unit }}</p>
      <el-button type="success" @click="calculateFootprint">计算</el-button>
    </div>

    <!-- 计算结果和建议 -->
    <el-card v-if="result !== null" class="result-card">
      <h3>计算结果</h3>
      <p>您的碳足迹: <strong>{{ result }} kgCO2</strong></p>
      <p>小贴士🌍：{{ loadingAdvice ? '加载中...' : advices }}</p>
      <el-button style="margin-left: 50%;width: 150px;margin-top: 20px" type="primary" @click="saveFootprintRecord">保存</el-button> <!-- Added Save Button -->
      <div style="margin-left: 85%">数据来源网络，仅供参考</div>

    </el-card>
  </div>
</template>


<style scoped>
.carbon-footprint-page {
  background-color: #f5f9f6;
  padding: 20px;
  color: #2b5d34;
}

h2 {
  margin-bottom: 20px;
  color: #388e3c;
}

.item-selection {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.calculation-section {
  margin-top: 20px;
  margin-left: 40%;
}

.result-card {
  background-color: #e8f5e9;
  border-color: #388e3c;
  color: #2b5d34;
  padding: 20px;
  margin-top: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.carousel-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
}
</style>
